package com.bw.module_mine.login.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.bw.lib_common.base.BaseViewModel
import com.bw.lib_common.base.state.Failed
import com.bw.lib_common.base.state.RequestEvent
import com.bw.lib_common.base.state.Success
import com.bw.lib_storage.mmkv.AuthMMKV
import com.bw.module_mine.login.model.LoginEntity
import com.bw.module_mine.login.model.RegisterEntity
import com.bw.module_mine.login.repository.UserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import javax.inject.Inject

@HiltViewModel
class UserViewModel @Inject constructor(private val repository: UserRepository) : BaseViewModel() {

    //保存当前正在显示的fragment
    private val _currentFragment = MutableStateFlow("")
    val currentFragment : StateFlow<String>
        get() = _currentFragment
    //请求发送验证码的时间
    var sendSmsCodeTimeStamp: Long = 0L

    val phone:MutableStateFlow<String> = MutableStateFlow("")
    val password:MutableStateFlow<String> = MutableStateFlow("")
    val registerPhone:MutableStateFlow<String> = MutableStateFlow("")
    val registerPassword:MutableStateFlow<String> = MutableStateFlow("")

    val registerPasswordAgain:MutableStateFlow<String> = MutableStateFlow("")
    fun setShowingFragmentTag(tag: String) {
        _currentFragment.value = tag
    }

    private val _LoginEvent = MutableSharedFlow<RequestEvent>()
    val LoginEvent get() = _LoginEvent.asSharedFlow()

    private val _RegisterEvent = MutableSharedFlow<RequestEvent>()
    val RegisterEvent get() = _RegisterEvent.asSharedFlow()

    fun login(password:String,username:String){
        execute(
            action = repository.login(password,username),
            onFinish = {
                _LoginEvent.emit(Success)

                AuthMMKV.token = it.data.token
                AuthMMKV.userid = it.data.id
                AuthMMKV.username = it.data.username
            },
            onError = {
                _LoginEvent.emit(Failed(it))
            }
        )
    }

    fun register(password:String,username:String){
        execute(
            action = repository.register(password,username),
            onFinish = {
                _RegisterEvent.emit(Success)

            },
            onError = {
                _RegisterEvent.emit(Failed(it))
            }
        )
    }



}